Use case: User application erase in interrupt mode ¶
Use case applicable in HAL2 only for FLASH.
Important
Interrupt-mode erase operations in HAL2 are granular and callback-driven.
Instead of passing a filled erase init structure (
FLASH_EraseInitTypeDef) like HAL1,
you invoke a dedicated
*_IT
API (for example,
HAL_FLASH_EraseByAddr_IT) whose parameters fully describe the target.
When callback registration is enabled, register the appropriate completion callback
(for example,
HAL_FLASH_RegisterEraseByAddrCpltCallback).
Page alignment still applies: an address range intersecting a page causes the whole page(s) to be erased.
Sequence diagram ¶
Code snippet ¶
|
HAL1 |
HAL2 |
|---|---|
uint32_t FirstPage = GetPage(FLASH_USER_START_ADDR);
uint32_t NbOfPages = GetPage(FLASH_USER_END_ADDR) - FirstPage + 1;
FLASH_EraseInitTypeDef EraseInitStruct;
/* NVIC configuration */
HAL_NVIC_SetPriority(FLASH_IRQn);
HAL_NVIC_EnableIRQ(FLASH_IRQn);
/* Unlock FLASH */
HAL_FLASH_Unlock();
/* Prepare erase parameters */
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Banks = BankNumber;
EraseInitStruct.Sector = FirstPage;
EraseInitStruct.NbSectors = NbOfPages;
/* Start interrupt erase */
HAL_StatusTypeDef status = HAL_FLASHEx_Erase_IT(&EraseInitStruct);
if (status != HAL_OK) { /* handle error */ }
/* Erase completion handled in callback */
void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
{
/* Application can update progress metrics here */
}
/* Lock FLASH */
HAL_FLASH_Lock();
|
hal_flash_handle_t flash_handle;
uint32_t start_addr = FLASH_START_ADDR;
uint32_t length_bytes = ERASE_LENGTH_BYTES;
/* NVIC configuration */
HAL_CORTEX_NVIC_SetPriority(FLASH_IRQn);
HAL_CORTEX_NVIC_EnableIRQ(FLASH_IRQn);
/* Initialization */
HAL_FLASH_Init(&flash_handle, HAL_FLASH);
/* Unlock interface */
HAL_FLASH_ITF_Unlock(HAL_FLASH);
/* Optional: register completion callback */
#if defined (USE_HAL_FLASH_REGISTER_CALLBACKS) && (USE_HAL_FLASH_REGISTER_CALLBACKS == 1)
HAL_FLASH_RegisterEraseByAddrCpltCallback(&flash_handle, EraseByAddrDone);
#endif
/* Start interrupt erase (address-range) */
hal_status_t status = HAL_FLASH_EraseByAddr_IT(&flash_handle, start_addr, length_bytes);
if (status != HAL_OK) { /* handle error */ }
void EraseByAddrDone(hal_flash_handle_t *h, uint32_t flash_addr, uint32_t size_byte)
{
/* flash_addr: first erased page address, size_byte: total erased bytes */
}
/* Lock interface */
HAL_FLASH_ITF_Lock(HAL_FLASH);
/* De-initialize */
HAL_FLASH_DeInit(&flash_handle);
|
Key changes ¶
HAL2 provides multiple
*_ITerase APIs (ByAddr/Page/Bank/Mass) instead of a single struct-based entry point.Completion is reported via handle-associated callbacks (optional registration), rather than only weak callbacks.
NVIC setup remains required, but the handler/callback chain is clarified by the IO/ITF separation.

